//
//  YSVipValidateView.m
//  Yueshi
//
//  Created by Northwan on 16/4/12.
//  Copyright © 2016年 悦食中国. All rights reserved.
//

#import "YSVipValidateView.h"
#import "UIImage+ImageEffects.h"

@interface YSVipValidateView()<YSPwdViewDelegate>
@property (strong, nonatomic) UIImageView *bgImageView;
@property (assign, nonatomic) BOOL keyboardIsShow;
@end

@implementation YSVipValidateView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

-(void)registNortif{
    //添加键盘弹出与隐藏的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)setupUI{
    self.width = SCREENW;
    self.height = SCREENH;
    
    UIImage *image = [[UIImage screenShot] applyLightEffect];
    UIImageView *bgImageView = [[UIImageView alloc]initWithImage:image];
    bgImageView.frame = self.bounds;
    [self addSubview:bgImageView];
    
    YSPwdView *pwdView = [YSPwdView pwdView];
    pwdView.delegate = self;
    pwdView.center = self.center;
    pwdView.size = CGSizeMake(270, 40);
    _pwdView = pwdView;
    [self addSubview:pwdView];
}

-(void)willMoveToSuperview:(UIView *)newSuperview{
    [self registNortif];
}

//-(void)show{
//    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
//    [window addSubview:self];
//    
//}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if(!self.keyboardIsShow){
        //移除键盘监听
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
        [super touchesBegan:touches withEvent:event];
    }else{
        [self endEditing:YES];
    }
}

- (void)keyboardWillShow:(NSNotification *)notif
{
    self.keyboardIsShow = YES;
    //在键盘显示的时候去调整View
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    //首页判断键盘有没有遮挡View，如果没有遮挡，那个什么也不做
    CGFloat viewMaxY = CGRectGetMaxY(_pwdView.frame);
    if (viewMaxY+SCALEX(10)>SCREENH-keyboardSize.height) {
        //代表键盘遮挡了view
        //需要将view移动
        [UIView animateWithDuration:0.25 animations:^{
            [_pwdView setY:SCREENH-keyboardSize.height-_pwdView.height-SCALEX(10)];
        }];
    }
}

-(void)keyboardWillHide:(NSNotification*)notif
{
    self.keyboardIsShow = NO;
    //在键盘隐藏的时候去调整View
    [UIView animateWithDuration:0.25 animations:^{
        [_pwdView setCenter:self.center];
    }];
}

-(void)inputFinish:(NSString *)pwdText{
    NSLog(@"%@",pwdText);
}

@end